package com.words.filter.auth;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.words.service.SecurityUserService;
import com.words.untils.JwtTokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//token过滤器
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JwtTokenUtils jwtTokenUtils;
    @Autowired
    SecurityUserService securityUserService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager){
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");

        if (token==null){   //token为空的话就不是自动登录，不需要在这里处理
            chain.doFilter(request,response);
            return;
        }

        Map<String,Object> map = new HashMap<>();
        try{
            jwtTokenUtils.verity(token);//验证令牌
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg","无效签名");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效");
        }
        //获取用户的权限等信息
        //现在每一个请求都会在这里，进行查库分配权限。为了性能，后面要解决掉这个问题

        String username=jwtTokenUtils.getVByToken(token,"username");
        UsernamePasswordAuthenticationToken token1
                = new UsernamePasswordAuthenticationToken(username,null,securityUserService.getUserAuthority(username));
        SecurityContextHolder.getContext().setAuthentication(token1);
        chain.doFilter(request,response);
        map.put("state",false);
    }
}
